/**
 * Global Variables can be used in every
 *
 * --logger                an global object used for logging
 * --mongoose            an global connection object used for accessing mongodb
 * --mysqlClient        an global connection object used for accessing mysql
 * --cacheClient            an global connection object used for accessing memCache or Redis depending the globalParameters pre-defined
 */


/**
 * Module dependencies.
 */
var express = require('express')
    , http = require('http')
    , path = require('path')
    , expressValidator = require('express-validator');

//var session = require('express-session');

var app = express();

if (!String.prototype.format) {
    String.prototype.format = function () {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined'
                ? args[number]
                : match
                ;
        });
    };
}

//app.use(session({
//    secret: '66xiaoqu',
//    name: '66xiaoqu',   //这里的name值得是cookie的name，默认cookie的name是：connect.sid
//    cookie: {maxAge: 1800000},  //设置maxAge是80000ms，即80s后session和相应的cookie失效过期
//    resave: false,
//    saveUninitialized: true
//}));

var bodyParser = require('body-parser');

//Set the environments for the application
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/server/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(bodyParser.json({limit:'500kb'}));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: 'some secret key'}));

app.use(express.methodOverride());
app.use(express.multipart());

app.use(app.router);

//Specify the html folder used for client - browser
app.use(express.static(path.join(__dirname, 'public')));


//load the log4js configuration
require('./server/config/logging');

var configPath = process.env.CONF_PATH;

//Development only
console.log('env===' + process.env.NODE_ENV);
console.log('configPath =' + configPath);
if ('DEV' == process.env.NODE_ENV) {
    require('./conf/globalParameters-DEV.js');
} else if ('TEST' == process.env.NODE_ENV) {
    require(configPath + '/66xiaoqu-app-conf/globalParameters-TEST.js');
} else if ('PROD' == process.env.NODE_ENV) {
    require(configPath + '/66xiaoqu-app-conf/globalParameters-PROD.js');
} else {
    logger.error('Please configure the environment Variable "NODE_ENV" in the OS system!');
    process.exit();
}

//node访问topic设置
//app.use("/topic", express.static(path.join(__dirname, resTopicPath())));

require('./server/config/globalParameters');
//Load the global parameters
require('./server/config/errorMessage');

//Load the database configuration
require('./server/config/database');

//Load the redis
require('./server/config/redis');

//Load the cache configuration;
require('./server/config/cache');


//load the log4js configuration
require('./server/config/messageQueue');

//load the log4js configuration
require('./server/config/passport');

//load the restClient
require('./server/config/restClient');

//load the fastDfsClient
require('./server/config/fdfsClient');

require('./server/config/hessian');
//load the baidu PushClient
require('./server/config/baiduPushClient');

//初始化权限列表
//require('./server/common/initialization/dataInit-step1');
//require('./server/common/initialization/market-release');

/**
 * load all of the routes;
 */
//================================================
require('./server/routes/index')(app);
require('./server/routes/filter-route')(app);
require('./server/routes/user-route')(app);
require('./server/routes/app-route')(app);
require('./server/routes/mutualAid-route')(app);
require('./server/routes/appLog-route')(app);
require('./server/routes/masterData-route')(app);
require('./server/routes/question-route')(app);
require('./server/routes/community-route')(app);
require('./server/routes/system-route')(app);
require('./server/routes/activity-route')(app);
require('./server/routes/score-route')(app);
require('./server/routes/lottery-route')(app);
require('./server/routes/market-route')(app);
require('./server/routes/group-route')(app);
require('./server/routes/task-route')(app);
require('./server/routes/mtOrder-route')(app);
//require('./server/routes/backoffice/backOffice-rest-route')(app);
//require('./server/routes/backoffice/backOffice-adminUser-route')(app);
//require('./server/routes/backoffice/backOffice-marketing-route')(app);
//require('./server/routes/backoffice/backOffice-lottery-route')(app);
//require('./server/routes/backoffice/backOffice-user-route')(app);
//require('./server/routes/backoffice/backOffice-activity-route')(app);
//require('./server/routes/backoffice/backOffice-question-route')(app);
//require('./server/routes/backoffice/backOffice-serviceAsUser-route')(app);
//require('./server/routes/backoffice/backOffice-voucher-route')(app);
//require('./server/routes/backoffice/backOffice-lotteryActivity-route')(app);
//require('./server/routes/backoffice/backOffice-banner-route')(app);
//require('./server/routes/backoffice/backoffice-scoreShop-route')(app);
//require('./server/routes/backoffice/backOffice-clientService-route')(app);
require('./server/routes/mobile/shares-route')(app);
require('./server/routes/mobile/downloadApp')(app);

// require('./server/routes/weixin/wish-route')(app);
// require('./server/routes/weixin/wechat-route')(app);

require('./server/routes/miniApp-route')(app);


/*宝宝树四期  精算-复核 业务模块 的路由文件  pzs 20171026  start**/
require('./server/routes/commission-route')(app);
/*宝宝树四期  精算-复核 业务模块 的路由文件  pzs 20171026  end**/

//================================================

if (BasicAuthen == 'Yes') {
    //Authenticate the request session;
    app.use(express.basicAuth(function (user, pass) {
        return user === '66xiaoqu' && pass === '66xiaoqu';
    }));
}

if (enableMultiProcessor == 'Yes') {
    //多进程模式
    /**
     * 先判断当前进程是否为主进程（cluster.isMaster），如果是的，就按照CPU的核数，新建若干个worker进程；
     * 如果不是，说明当前进程是worker进程，则在该进程启动一个服务器程序。
     */
    var cluster = require('cluster');
    var os = require('os');

    if (cluster.isMaster) {
        for (var i = 0, n = os.cpus().length; i < n; i += 1) {
            cluster.fork();
        }
    }
    else {
        httpServer = http.createServer(app);
        logger.info('Starting the back-end server....');
        //================================================
        httpServer.listen(app.get('port'), function () {
            logger.info('App server listening on port for Http Request: ' + app.get('port') + '...');
        });
    }

} else {

    //单进程模式
    httpServer = http.createServer(app);
    httpServer.setMaxListeners(0);
    logger.info('Starting the back-end server....');
    //================================================
    httpServer.listen(app.get('port'), function () {
        logger.info('App server listening on port for Http Request: ' + app.get('port') + '...');
    });

}
process.on('uncaughtException', function (err) {
    logger.error('Caught exception: ' + err);
});
